package com.hd.crdao.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.hd.crdao.BuildConfig;
import com.hd.crdao.R;
import com.hd.crdao.base.BaseSecondActivity;
import com.hd.crdao.config.Constants;
import com.hd.crdao.utils.ALog;
import com.hd.crdao.utils.DialogUtils;
import com.hd.crdao.utils.GetMobileInfoUtils;
import com.hd.crdao.utils.GlobalData;
import com.hd.crdao.utils.ImageUtil;
import com.hd.crdao.utils.MyToast;
import com.hd.crdao.utils.SPUtils;
import com.hd.crdao.utils.UIUtils;
import com.hd.crdao.view.ExpandHeadView;
import com.hd.crdao.wrapper.GlideImageUtils;
import com.hd.crdao.wrapper.UpFileCallBack;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;

/**
 *
 *@author Programming
 *@date 2017/7/12 0012
 */
public class CarCheckPhotoActivity extends BaseSecondActivity implements View.OnClickListener {


    private static final int FROM_CAMERA = 101;
    public LocationClient mLocationClient;
    public BDLocationListener myListener = new MyLocationListener();
    @BindView(R.id.carcheckphoto_head)
    ExpandHeadView mCarcheckphotoHead;
    @BindView(R.id.VINphoto)
    ImageView mVINphoto;
    @BindView(R.id.take_VINphoto)
    LinearLayout mTakeVINphoto;
    @BindView(R.id.carsurface)
    ImageView mCarsurface;
    @BindView(R.id.take_carsurface)
    LinearLayout mTakeCarsurface;
    @BindView(R.id.tvLocation)
    TextView mTvLocation;
    @BindView(R.id.getlocation)
    TextView mGetlocation;
    public ArrayList<String> imagePaths = new ArrayList<>();
    private int count = 0;

    @Override
    protected int setContentView() {
        return R.layout.activity_carcheckphoto;
    }

    @Override
    protected ExpandHeadView setExpandHeadView() {
        return mCarcheckphotoHead;
    }

    @Override
    protected void initView() {
        imagePaths.add(0, "");
        imagePaths.add(1, "");
        initBaiduLocation();
        initEvent();
    }

    /**
     *
     */
    private void initEvent() {
        mGetlocation.setOnClickListener(this);
        mTakeCarsurface.setOnClickListener(this);
        mTakeVINphoto.setOnClickListener(this);
        mCarcheckphotoHead.getHeadViewRightText().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVINphoto.getDrawable() == null || TextUtils.isEmpty(imagePaths.get(0))) {
                    MyToast.show("请上传车架号照片");
                    return;
                } else if (mCarsurface.getDrawable() == null || TextUtils.isEmpty(imagePaths.get(1))) {
                    MyToast.show("请上传车辆正面照片");
                    return;
                }

                UploadSomeInfo();


            }
        });
    }

    /**
     * 上传一些信息
     * 输  入	userId	用户ID
     * vehicleId	车辆ID
     * latlon	纬度经度逗号隔开  如：119.275382,26.114709
     * cmmii	手机序列
     * images[]	照片数组
     * imageNames[]	图片名称数组
     */
    private void UploadSomeInfo() {
        boolean temp = true;
        for (int i = 0; i < imagePaths.size(); i++) {
            if (!judgePicture(imagePaths.get(i))) {
                MyToast.show("图片太小,可能导致不清晰,请重拍后再试!");
                temp = false;
                break;
            }
        }
        if (!temp) {
            return;
        }

        DialogUtils.createProgressDialog(CarCheckPhotoActivity.this, "正在上传中...").show();
        HashMap<String, String> map = new HashMap<>();
        String userId = SPUtils.getString("userid", "");
        String vehicleId = SPUtils.getString("vehicleId", "");
        String latLon = SPUtils.getString("latLon", "");
        String cmmii = GetMobileInfoUtils.getDeviceId(this);
        map.put("sign", Constants.SIGN);
        map.put("userId", userId);
        map.put("vehicleId", vehicleId);
        map.put("latlon", latLon);
        map.put("cmmii", cmmii);
        map.put("imageNames", "车架号,车辆正面");
        map.put("record", getComment());

        OkHttpUtils.post().url(Constants.CARCHECK_URL)
                .params(map)
                .addFile("images", imagePaths.get(0), new File(imagePaths.get(0)))
                .addFile("images", imagePaths.get(1), new File(imagePaths.get(1)))
                .build().execute(new UpFileCallBack() {
                                     @Override
                                     public void onUpFileFinished() {
                                     }

                                     @Override
                                     protected void onFailed(String message) {
                                         MyToast.show(message);
                                     }

                                     @Override
                                     protected void onSuccess(String message) {
                                         MyToast.show("上传成功");
                                     }

                                     @Override
                                     public void onAfter(int id) {
                                         DialogUtils.dismiss();
                                         finish();
                                         super.onAfter(id);
                                     }
                                 }

        );

    }

    /**
     * 判断图片是否符合上传规则(是否大于200K)
     *
     * @param fileName
     * @return
     */
    public boolean judgePicture(String fileName) {
        File file = new File(fileName);
        return file.exists() && file.length() > 200 * 1024;
    }

    private void initBaiduLocation() {
        mLocationClient = new LocationClient(UIUtils.getContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        initLocation();
        mLocationClient.start();
        if (TextUtils.equals("定位失败", mTvLocation.getText().toString())) {
            MyToast.show("定位失败，请检查网络是否可用!");
        }

    }

    /**
     * 初始化定位的信息
     */
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);
        //可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps
        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.getlocation:
                mLocationClient.requestLocation();
                break;
            case R.id.take_VINphoto:
                count = 0;
                upLoadIdcardImage();
                break;

            case R.id.take_carsurface:
                count = 1;
                upLoadIdcardImage();
                break;

        }
    }

    /**
     * 手机参数依次是:安卓系统,手机品牌,手机型号,当前APP版本
     *
     * @return 获取备注信息
     */
    public String getComment() {
        String androidOs = GetMobileInfoUtils.getSystemVersion();
        String mobileBrand = GetMobileInfoUtils.getDeviceBrand();
        String mobileModel = GetMobileInfoUtils.getSystemModel();
        String appVersion = BuildConfig.VERSION_NAME;
        return androidOs + "," + mobileBrand + "," + mobileModel + "," + appVersion;
    }


    /**
     * 照片拍照的弹框及操作
     */
    private void upLoadIdcardImage() {
        View parent = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
        View popView = View.inflate(this, R.layout.camera_pop_menu, null);

        Button btnCamera = (Button) popView.findViewById(R.id.btn_camera_pop_camera);
        Button btnAlbum = (Button) popView.findViewById(R.id.btn_camera_pop_album);
        btnAlbum.setVisibility(View.GONE);
        Button btnCancel = (Button) popView.findViewById(R.id.btn_camera_pop_cancel);
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels;
        final PopupWindow popWindow = new PopupWindow(popView, width, height);
        popWindow.setAnimationStyle(R.style.AnimBottom);
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        ColorDrawable dw = new ColorDrawable(0x30000000);
        popWindow.setBackgroundDrawable(dw);
        popWindow.showAtLocation(parent, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

        btnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //打开系统照相机
                openSystemCamera();
                popWindow.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
    }


    private String fileName;

    /**
     * 打开系统相机---已经进行版本适配
     */
    private void openSystemCamera() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File parent = new File(GlobalData.CameraFile);
        if (!parent.exists()) {
            parent.mkdirs();
        }
        File file = new File(parent, System.currentTimeMillis() + ".jpg");
        Uri imageUri = FileProvider.getUriForFile(CarCheckPhotoActivity.this, getPackageName() + ".provider", file);
        ALog.d(file.getAbsolutePath());

        fileName = file.getAbsolutePath();
        //指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        /// intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
        startActivityForResult(intent, FROM_CAMERA);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FROM_CAMERA & resultCode == RESULT_OK) {
            Bitmap bitmap = BitmapFactory.decodeFile(fileName);
            File file = new File(fileName);
            if (file.exists() && file.length() >  1024 * 1024) {
                boolean b = ImageUtil.savePressBitmap(file, bitmap);
            }
            getPicture();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 获得相片 并设置进去
     *
     * @param
     */
    private void getPicture() {
        if (count == 0) {
            GlideImageUtils.loadImage(fileName,R.drawable.vin_2x,mVINphoto);
            //Glide.with(UIUtils.getContext()).load(fileName).placeholder(R.drawable.vin_2x).into(mVINphoto);
        } else if (count == 1) {
            GlideImageUtils.loadImage(fileName,R.drawable.carpic_2x,mCarsurface);
           // Glide.with(UIUtils.getContext()).load(fileName).placeholder(R.drawable.carpic_2x).into(mCarsurface);
        }
        imagePaths.set(count, fileName);

    }


    @Override
    protected void onDestroy() {
        if (mLocationClient != null) {
            mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(myListener);
        }
        super.onDestroy();
    }

    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getAddrStr() != null) {
                //获取定位结果
                StringBuilder sb = new StringBuilder(256);
                mTvLocation.setText(sb.append(location.getAddrStr()).toString());
                mLocationClient.stop();
            } else {
                mTvLocation.setText("定位失败");
            }
        }
    }
}
